import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;

public class AudioChecker {

    /**
     * 检查音频文件的采样率和声道数
     *
     * @param filePath 音频文件路径
     * @throws UnsupportedAudioFileException 如果音频文件格式不支持
     * @throws IOException                  如果文件读取失败
     */
    public static void checkAudioFile(String filePath) throws UnsupportedAudioFileException, IOException {
        File audioFile = new File(filePath);
        if (!audioFile.exists()) {
            throw new IOException("音频文件不存在: " + filePath);
        }

        try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile)) {
            AudioFormat format = audioInputStream.getFormat();
            float sampleRate = format.getSampleRate(); // 采样率
            int channels = format.getChannels();      // 声道数

            System.out.println("音频文件: " + filePath);
            System.out.println("采样率: " + sampleRate + " Hz");
            System.out.println("声道数: " + channels);

            // 检查采样率和声道数是否符合要求
            if (sampleRate != 16000) {
                throw new IllegalArgumentException("采样率必须为16000Hz，当前为: " + sampleRate + " Hz");
            }
            if (channels != 1) {
                throw new IllegalArgumentException("声道数必须为1（单声道），当前为: " + channels);
            }
        }
    }

    public static void main(String[] args) {
        String audioFilePath = "./win.wav"; // 替换为你的音频文件路径
        try {
            checkAudioFile(audioFilePath);
            System.out.println("音频文件符合要求");
        } catch (Exception e) {
            System.err.println("音频文件检查失败: " + e.getMessage());
        }
    }
}